var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
(function (factory) {
    if (typeof module === "object" && typeof module.exports === "object") {
        var v = factory(require, exports);
        if (v !== undefined) module.exports = v;
    }
    else if (typeof define === "function" && define.amd) {
        define(["require", "exports", "../../../com/configTool", "../Util/initDB", "axios", "crypto", "../Util/readFromDB", "../Util/saveToDB", "../../../com/DBTool/DBConnectTool"], factory);
    }
})(function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    const configTool_1 = __importDefault(require("../../../com/configTool"));
    const initDB_1 = __importDefault(require("../Util/initDB"));
    const axios_1 = __importDefault(require("axios"));
    const crypto_1 = __importDefault(require("crypto"));
    const readFromDB_1 = __importDefault(require("../Util/readFromDB"));
    const saveToDB_1 = __importDefault(require("../Util/saveToDB"));
    const DBConnectTool_1 = __importDefault(require("../../../com/DBTool/DBConnectTool"));
    let Loading = true;
    const DBName = 'tile.googleapis.com';
    const Cesium = require('cesium/Build/Cesium/index.cjs');
    const defaultAccessToken = Cesium.Ion.defaultAccessToken;
    let key = '';
    let session = '';
    async function getWallData(url, responseType = 'json') {
        return new Promise((resolve, reject) => {
            axios_1.default
                .get(url, {
                responseType: responseType,
                proxy: {
                    protocol: 'http',
                    host: '127.0.0.1',
                    port: 7890
                }
            })
                .then(e => resolve(e.data))
                .catch(e => resolve(null));
        });
    }
    let Google3DTiles = {
        async init() {
            if (Loading) {
                Loading = false;
                await configTool_1.default.init();
                configTool_1.default.preservableONDB() && await (0, initDB_1.default)(DBName);
            }
        },
        async getRootJson() {
            await this.init();
            await (0, initDB_1.default)(DBName);
            await DBConnectTool_1.default.openDB(DBName);
            const endpointUrl = 'https://api.cesium.com/v1/assets/2275207/endpoint?access_token=' + defaultAccessToken;
            try {
                const authority = await fetch(endpointUrl).then(e => e.json());
                const rootUrl = authority.options.url;
                const rootJson = await getWallData(rootUrl, 'json');
                let tileSetRootRelativeUri = rootJson.root.children[0].children[0].content.uri;
                key = new URL(rootUrl).searchParams.get('key') || '';
                const tileSetRootUri = `https://tile.googleapis.com${tileSetRootRelativeUri}&key=${key}`;
                session = new URL(tileSetRootUri).searchParams.get('session') || '';
                tileSetRootRelativeUri = tileSetRootRelativeUri.split('?').shift();
                const { json: tileSetRoot } = await this.getJson(tileSetRootRelativeUri);
                return { key, session, tileSetRoot };
            }
            catch (e) {
                console.error('获取 GooglePhotorealistic3DTileSet 失败');
                return null;
            }
        },
        async hasFile(uri) {
            const dbPath = uri.replaceAll('/', '\\');
            const dbTool = await DBConnectTool_1.default.openDB(DBName);
            if (await dbTool.getFileByFullPath(dbPath)) {
                return true;
            }
            else {
                return false;
            }
        },
        async getJson(uri, needSaveToDB = true) {
            const { buffer, dataSource } = await this.getBuffer(uri, needSaveToDB, true);
            return { json: JSON.parse(buffer.toString()), dataSource };
        },
        async getBuffer(uri, needSaveToDB = true, needCompress = false) {
            const dbPath = uri.replaceAll('/', '\\');
            let [err, buffer, dataSource] = await (0, readFromDB_1.default)({ DBName: DBName, relativePath: dbPath });
            if (!buffer) {
                buffer = await getWallData(`https://tile.googleapis.com${uri}?session=${session}&key=${key}`, 'arraybuffer');
                dataSource = 'Net';
                if (needSaveToDB) {
                    const md5Str = crypto_1.default.createHash('md5').update(buffer).digest('hex');
                    if (md5Str) {
                        (0, saveToDB_1.default)({ DBName: DBName, relativePath: dbPath, buffer }, needCompress).then();
                    }
                }
            }
            return { err, buffer, dataSource };
        }
    };
    exports.default = Google3DTiles;
});
